from django.shortcuts import render,HttpResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from configuration.sms_code import send_message
import string
import json
import random
from captcha.image import ImageCaptcha
import redis
import jwt
from business.models import *
import time
from django.conf import settings
from configuration.jwt_decode import check_login
from django.core.paginator import Paginator
from werkzeug.security import check_password_hash, generate_password_hash
import requests
from bs4 import BeautifulSoup
import random
from datetime import datetime
from configuration.redis_packaging import RedisPackaging
# Create your views here.
# 商家视图


# 图片验证码的视图
class ImageCodeAPIView(APIView):
    def get(self, request, uuid):
        # 生成一个4位数随机码
        # string.ascii_letters：a-zA-Z所有字母
        # string.digits：数字0-9
        # random.sample：随机采样(返回列表类型)
        code = "".join(random.sample(string.ascii_letters + string.digits, 4))
        # 实例化一个图片验证码对象
        # 用captcha.image下的 ImageCaptcha 生成字符验证码图片
        img = ImageCaptcha()
        # 把这个验证码转换成图片形式的
        image_code = img.generate(code)  # 字节io对象
        # 验证码存入redis
        rds = RedisPackaging()
        rds.add(uuid, code)

        # 返回响应
        return HttpResponse(image_code, content_type="image/png")


# 获取验证码
class SmsView(APIView):
    def get(self,request,mobile):
        uuid = request.query_params.get('uuid')
        code = request.query_params.get('code')
        if not all([uuid,code]):
            return Response({
                'code':400,
                'msg':'获取数据为空'
            })
        print('>>>>>>>>>>',uuid,code)
        # 取出redis中uuid的值
        rds = RedisPackaging()
        code_r = rds.gain(uuid)
        if not code_r:
            return Response({
                'code':400,
                'msg':'校验码已过期'
            })
        # 验证码还未过期，解码与前端对比
        if code_r.decode().lower() != code.lower():
            return Response({
                "code": 400,
                "msg": "校验码错误"
            })

        send_message(mobile)
        return Response({
            'code':200,
            'msg':'发送成功'
        })


# 手机验证码登入或注册
class UserView(APIView):
    def get(self,request):
        # 接受前端token
        deng = request.query_params.get('token')
        key = settings.SECRET_KEY
        token = jwt.decode(deng, key=key, algorithms='HS256')
        print('token的', token)

        u_id = token.get("uid")
        print('dasdasd',u_id)

        try:
            user = BusUserModel.objects.get(id=u_id)
        except Exception as e:
            print('>>>>>>>>>',e)
            return Response({
                'code':40000,
                'message':'获取失败'
            })

        return Response({
            'code':20000,
            'message':'获取成功',
            'data':{
                'roles': '商家',
                'name': user.b_name,
                'avatar': user.portrait,
            },


        })


    def post(self,request):
        mobile = request.data.get('mobile')
        sms = request.data.get('sms')
        if not all([mobile,sms]):
            return Response({
                'code':40000,
                'message':'获取数据为空'
            })

        # 取出redis中uuid的值
        rds = RedisPackaging()
        key = 'sms_%s' % mobile
        code_r = rds.gain(key)
        if not code_r:
            return Response({
                'code': 40000,
                'message': '验证码已过期'
            })
        # 验证码还未过期，解码与前端对比
        if code_r.decode().lower() != sms.lower():
            return Response({
                "code": 40000,
                "message": "验证码错误"
            })

        # 判断此手机号是否注册
        user = BusUserModel.objects.filter(mobile=mobile)
        if not user:
            b_name = '商家%s' % mobile
            # 没有注册，进行注册
            BusUserModel.objects.create(
                mobile=mobile,
                b_name=b_name,
                portrait='http://rm0i9f70z.bkt.clouddn.com/002437-16696526778c24.jpg',
                person='1'
            )
        try:
            user = BusUserModel.objects.get(mobile=mobile)
        except Exception as e:
            return Response({
                'code':40000,
                'message':'没有此信息'
            })

        token = jwt.encode({
            'uid':user.id,
            'username':user.b_name,
            'exp':time.time() + 720000
        },key=settings.SECRET_KEY,algorithm='HS256')

        return Response({
            'code':20000,
            'message':'登入成功',
            'data':{
                'token': token,
                'uid': user.id,
                "character": '商家',
            },
            'person': user.person,
        })


# 对商品类别的增删改查  在平台操作
class ClassifyView(APIView):
    def get(self,request):
        # 获取所有分类
        category = CategoryModel.objects.filter(delete=False)
        category_list = []
        for i in category:
            category_list.append({
                'id':i.id,
                'c_name':i.c_name,
                'c_img':i.c_img,
            })

        return Response({
            'code':200,
            'msg':'获取分类商品成功',
            'data':category_list,
        })

    def post(self,request):
        c_name = request.data.get('name')
        c_img = request.data.get('img')

        if not all([c_img,c_name]):
            return Response({
                'code':400,
                'msg':'获取的数据为空'
            })

        # 唯一性判断
        category = CategoryModel.objects.filter(c_name=c_name)
        if category:
            return Response({
                'code':400,
                'msg':'已有此分类'
            })

        CategoryModel.objects.create(
            c_name=c_name,
            c_img=c_img,
        )

        return Response({
            'code':200,
            'msg':"添加成功"
        })

# 商品分类的编辑获取删除
class ClassifyInfoView(APIView):
    def get(self,request,id):
        try:
            category = CategoryModel.objects.get(id=id)
            return Response({
                'code':200,
                'msg':'获取成功',
                'data':{
                    'cid':category.id,
                    'c_name':category.c_name,
                    'c_img':category.c_img,
                }
            })
        except Exception as e:
            print(">?>>>>>",e)
            return Response({
                'code':400,
                'msg':'获取商品分类失败'
            })

    def put(self,request,id):
        # 获取前端数据
        c_name = request.data.get('name')
        c_img = request.data.get('img')

        if not all([c_img, c_name]):
            return Response({
                'code': 400,
                'msg': '获取的数据为空'
            })

        try:
            category = CategoryModel.objects.get(id=id)
            category.c_name = c_name
            category.c_img = c_img
            category.save()

            return Response({
                'code':200,
                'msg':'商品分类修改成功'
            })

        except Exception as e:
            print(">?>>>>>",e)
            return Response({
                'code':400,
                'msg':'获取商品分类失败'
            })

    def delete(self,request,id):
        try:
            category = CategoryModel.objects.get(id=id)
            category.delete = True
            category.save()
            return Response({
                'code':200,
                'msg':'删除成功'
            })

        except Exception as e:
            print(">>>>>>>",e)
            return Response({
                'code':400,
                'msg':'没有此分类'
            })


# 商品的增删改查
class GoodsView(APIView):
    def get(self,request):
        currentPage = request.query_params.get('page')
        pageSize = request.query_params.get('page_size')
        name = request.query_params.get('name')
        print('>>>>>>>>>>',name)

        name = json.loads(name)
        goods = GoodsModel.objects
        if name['name']:
            goods = goods.filter(g_name=name['name'])

        goods = goods.filter(delete=False)

        # 分页数据
        paginator = Paginator(goods, pageSize)
        # 获取当前页面  currentPage：页码
        page = paginator.page(currentPage)

        # 获取当前页面中的数据(商品对象) object_list:查询集
        data = page.object_list

        goods_list = []
        for i in data:
            goods_list.append({
                'id':i.id,
                'g_name':i.g_name,
                'volume':i.volume,
                'inventory':i.inventory,
                'price':i.price,
                'img':i.img,
                'category':i.category_id,
                'cate':i.category.c_name,
                'bus_user':i.bus_user_id,
                'user':{
                    'u_name':i.bus_user.nickname,
                    'portrait':i.bus_user.portrait,
                    'mobile':i.bus_user.mobile,
                    'business_time':i.bus_user.business_time,
                },
                'burdening':i.burdening,
                'establish_time':datetime.strftime(i.establish_time,'%Y-%m-%d %H:%M:%S'),
                'is_recommend':i.is_recommend,
                'is_demand':i.is_demand
            })

        return Response({
            'code':200,
            'msg':'商品获取成功',
            'data':goods_list,
            'total':goods.count(),
        })

    @check_login
    def post(self,request):
        # 获取前端数据
        u_id = request.uid
        print('>>>>>>>>>>',u_id)
        g_name = request.data.get('g_name')
        inventory = request.data.get('inventory')
        price = request.data.get('price')
        img = request.data.get('img')
        category = request.data.get('category')
        burdening = request.data.get('burdening')
        store = request.data.get('store')

        print('>>>>>>>>',g_name,inventory,price,img,category,store)

        if not all([g_name,inventory,price,img,category,store]):
            return Response({
                'code':400,
                'msg':'获取前端数据失败'
            })

        GoodsModel.objects.create(
            g_name=g_name,
            inventory=inventory,
            price=price,
            img=img,
            category_id=int(category),
            bus_user_id=u_id,
            burdening=burdening,
            store_id=int(store),
        )

        return Response({
            'code':200,
            'msg':"菜品添加成功"
        })

# 获取所有自己的店铺
class OneselfStoreView(APIView):
    @check_login
    def get(self,request):
        u_id = request.uid
        store = StoreModel.objects.filter(bus_user_id=u_id)
        store_list = []
        for i in store:
            store_list.append({
                'id':i.id,
                'store':i.store,
                'site':i.site,
                'is_default':i.is_default,
                'bus_user_id':i.bus_user_id,
                'establish_time':i.establish_time,
                'change_time':i.change_time,
            })
        return Response({
            'code':20000,
            'msg':'获取成功',
            'data':store_list
        })



# 获取商家自己的商品
class OneselfGoodsView(APIView):
    @check_login
    def get(self,request):
        u_id = request.uid
        currentPage = request.query_params.get('page')
        pageSize = request.query_params.get('page_size')
        name = request.query_params.get('name')

        name = json.loads(name)
        goods = GoodsModel.objects

        if name['name']:
            goods = goods.filter(g_name=name['name'])

        goods = goods.filter(delete=False,bus_user_id=u_id)

        # 分页数据
        paginator = Paginator(goods, pageSize)
        # 获取当前页面  currentPage：页码
        page = paginator.page(currentPage)

        # 获取当前页面中的数据(商品对象) object_list:查询集
        data = page.object_list

        goods_list = []
        for i in data:
            goods_list.append({
                'id': i.id,
                'g_name': i.g_name,
                'volume': i.volume,
                'inventory': i.inventory,
                'price': i.price,
                'img': i.img,
                'category': i.category_id,
                'cate': i.category.c_name,
                'bus_user': i.bus_user_id,
                'user': {
                    'u_name': i.bus_user.b_name,
                    'portrait': i.bus_user.portrait,
                    'mobile': i.bus_user.mobile,
                    'business_time': i.bus_user.business_time,
                },
                'burdening': i.burdening,
                'establish_time': datetime.strftime(i.establish_time, '%Y-%m-%d %H:%M:%S'),
                'is_recommend': i.is_recommend,
                'is_demand': i.is_demand
            })

        return Response({
            'code': 200,
            'msg': '商品获取成功',
            'data': goods_list,
            'total': goods.count(),
        })

# 商品的修改删除获取
class GoodsInfoView(APIView):
    @check_login
    def get(self,request,id):
        u_id = request.uid
        try:
            good = GoodsModel.objects.get(id=id)
            return Response({
                'code':200,
                'msg':'获取成功',
                'data':{
                    'id': good.id,
                    'g_name': good.g_name,
                    'volume': good.volume,
                    'inventory': good.inventory,
                    'price': good.price,
                    'img': good.img,
                    'category': good.category_id,
                    'bus_user': good.bus_user_id,
                    'store':good.store_id,
                    'user': {
                        'u_name': good.bus_user.b_name,
                        'portrait': good.bus_user.portrait,
                        'mobile': good.bus_user.mobile,
                        'business_time': good.bus_user.business_time,
                    },
                    'burdening':good.burdening,


                }
            })
        except Exception as e:
            print('>>>>>>>>>>',e)
            return Response({
                'code':400,
                'msg':'没有此商品'
            })

    @check_login
    def put(self,request,id):
        g_name = request.data.get('g_name')
        inventory = request.data.get('inventory')
        price = request.data.get('price')
        img = request.data.get('img')
        category = request.data.get('category')
        store = request.data.get('store')

        if not all([g_name,inventory,price,img,category,store]):
            return Response({
                'code':400,
                'msg':'获取前端数据失败'
            })

        # 判断是不是你的商品
        u_id = request.uid
        try:
            good = GoodsModel.objects.get(id=id)
            if good.bus_user_id == u_id:

                good.g_name = g_name
                good.inventory = inventory
                good.price = price
                good.img = img
                good.category_id = category
                good.store_id = store
                good.save()

                return Response({
                    'code':200,
                    'msg':'商品修改成功'
                })
            return Response({
                'code':400,
                'msg':'此商品不是你的不可修改'
            })

        except Exception as e:
            print(">?>>>>>",e)
            return Response({
                'code':400,
                'msg':'商品修改失败'
            })

    @check_login
    def delete(self,request,id):
        u_id = request.uid
        try:
            good = GoodsModel.objects.get(id=id)
            if good.bus_user_id == u_id:

                good.delete = True
                good.save()

                return Response({
                    'code':200,
                    'msg':'删除成功'
                })
            return Response({
                'code':400,
                'msg':'此商品不是你的不可删除'
            })

        except Exception as e:
            print('>>>>>>>>>>>',e)
            return Response({
                'code':400,
                'msg':'删除失败'
            })


# 获取主食分类商品
class CateGoodView(APIView):
    def get(self,request,id):
        # 判断分类是否存在
        try:
            category = CategoryModel.objects.get(id=id)
            print('>>>>>>>>',category)
        except Exception as e:
            return Response({
                'code':400,
                'msg':'获取分类失败'
            })

        goods = GoodsModel.objects.filter(category_id=id)
        goods_list = []
        for i in goods:
            goods_list.append({
                'id':i.id,
                'g_name':i.g_name,
                'volume':i.volume,
                'inventory':i.inventory,
                'price':i.price,
                'img':i.img,
                'category':i.category_id,
                'bus_user':i.bus_user_id,
                'establish_time':i.establish_time,
                'change_time':i.change_time,
                'delete':i.delete,
                'burdening':i.burdening,
            })
        c_name = category.c_name
        return Response({
            'code':200,
            'msg':'获取商品成功',
            'data':goods_list,
            'c_name':c_name
        })


# 获取推荐畅销的商品
class RecommendView(APIView):
    def get(self,request,id):
        if id == 4:
            goods = GoodsModel.objects.filter(is_recommend=True,delete=False)
            goods_list = []
            for i in goods:
                goods_list.append({
                    'id':i.id,
                    'g_name': i.g_name,
                    'volume': i.volume,
                    'inventory': i.inventory,
                    'price': i.price,
                    'img': i.img,
                    'category': i.category_id,
                    'bus_user': i.bus_user_id,
                    'establish_time': i.establish_time,
                    'change_time': i.change_time,
                    'delete': i.delete,
                    'burdening': i.burdening,
                })
            return Response({
                'code': 200,
                'msg': "获取推荐商品成功",
                'data': goods_list,
            })
        else:
            goods = GoodsModel.objects.filter(is_demand=True,delete=False)
            goods_list = []
            for i in goods:
                goods_list.append({
                    'id':i.id,
                    'g_name': i.g_name,
                    'volume': i.volume,
                    'inventory': i.inventory,
                    'price': i.price,
                    'img': i.img,
                    'category': i.category_id,
                    'bus_user': i.bus_user_id,
                    'establish_time': i.establish_time,
                    'change_time': i.change_time,
                    'delete': i.delete,
                    'burdening': i.burdening,
                })
            return Response({
                'code':200,
                'msg':"获取推荐商品成功",
                'data':goods_list,
            })

# 获取单个商品
class GoodInfoView(APIView):
    def get(self,request,id):
        try:
            goods = GoodsModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code':400,
                'msg':'获取失败'
            })

        return Response({
            'code':200,
            'msg':'获取成功',
            'data':{
                'id': goods.id,
                'g_name': goods.g_name,
                'volume': goods.volume,
                'inventory': goods.inventory,
                'price': goods.price,
                'img': goods.img,
                'category': goods.category_id,
                'bus_user': goods.bus_user_id,
                'establish_time': goods.establish_time,
                'change_time': goods.change_time,
                'delete': goods.delete,
                'burdening': goods.burdening,
            }
        })


# 获取商家入驻 商家入驻
class EnterView(APIView):
    # 获取入驻信息
    @check_login
    def get(self,request):
        uid = request.uid

        try:
            bus = BusUserModel.objects.get(id=uid,is_audit=1)
        except Exception as e:
            return Response({
                'code':40000,
                'messag':'a'
            })

        store = StoreModel.objects.filter(is_default=True, bus_user_id=uid).first()
        try:
            name = store.store
            addr = store.site
        except Exception as e:
            return Response({
                'code':40000,
                'message':'商家未入驻',
            })


        return Response({
            'code':20000,
            'message':'获取成功',
            'data':{
                'id':bus.id,
                'name':name,
                'addr':addr,
                'identity':bus.identity,
                'b_name':bus.b_name,
                'mobile':bus.mobile,
                'person':bus.person,
                'facade':bus.facade,
                'plaque':bus.plaque,
                'environment':bus.environment,
                'business':bus.business,
                'hand_identity':bus.hand_identity,
                'identity_front':bus.identity_front,
                'identity_reverse':bus.identity_reverse,
            }
        })


    @check_login
    def put(self,request):
        # 获取id
        id = request.uid
        # 获取前端数据
        name = request.data.get('name')
        addr = request.data.get('addr')
        identity = request.data.get('identity')
        b_name = request.data.get('b_name')
        person = request.data.get('person')
        facade = request.data.get('facade')
        plaque = request.data.get('plaque')
        environment = request.data.get('environment')
        business = request.data.get('business')
        hand_identity = request.data.get('hand_identity')
        identity_front = request.data.get('identity_front')
        identity_reverse = request.data.get('identity_reverse')

        if not all([name,addr,identity,b_name,person,facade,plaque,environment,business,hand_identity,identity_front,identity_reverse]):
            return Response({
                'code':40000,
                'message':'获取前端数据为空'
            })

        store = StoreModel.objects.filter(store=name,bus_user_id=id).first()
        if not store:
            StoreModel.objects.create(
                store=name,
                bus_user_id=id,
                site=addr,
                is_default=True,
            )
        else:
            store.store = name
            store.site = addr
            store.save()

        try:
            bus = BusUserModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code':40000,
                'message':'获取失败'
            })

        # 进行修改
        bus.b_name = b_name
        bus.person = person
        bus.facade = facade
        bus.plaque = plaque
        bus.environment = environment
        bus.business = business
        bus.hand_identity = hand_identity
        bus.identity_front = identity_front
        bus.identity_reverse = identity_reverse
        bus.identity = identity
        bus.is_audit = 3
        bus.save()

        return Response({
            'code':20000,
            'message':'提交成功，等待审核'
        })


# 商家个人信息的修改
class MerchantInfoView(APIView):
    @check_login
    def get(self,request):
        u_id = request.uid
        try:
            bus = BusUserModel.objects.get(id=u_id)
        except Exception as e:
            return Response({
                'code':400,
                'msg':'没有此数据'
            })


        return Response({
            'code':200,
            'msg':'获取成功',
            'data':{
                'nickname':bus.nickname,
                'portrait':bus.portrait,
                'gender':bus.gender,
            }
        })



    @check_login
    def put(self,request):
        u_id = request.uid

        # 接受前端数据
        nickname = request.data.get('nickname')
        password = request.data.get('password')
        passwords = request.data.get('passwords')
        portrait = request.data.get('portrait')
        gender = request.data.get('gender')

        if password != passwords:
            return Response({
                'code':400,
                'msg':"前后密码不一致"
            })
        print('>>>>>>>>,',nickname,password,passwords,portrait,gender)
        if not all([nickname,password,passwords,portrait,gender]):
            return Response({
                'code':400,
                'msg':'获取数据失败'
            })
        try:
            bus = BusUserModel.objects.get(id=u_id)
        except Exception as e:
            return Response({
                'code':400,
                'msg':'没有此数据'
            })

        bus.nickname = nickname
        bus.gender = gender
        bus.portrait = portrait
        # 密码加密
        if password != '':
            password_k = generate_password_hash(password)
            bus.password = password_k
        bus.save()

        return Response({
            'code':200,
            'msg':'修改成功'
        })


# 获取店铺信息
class StoreInfoView(APIView):
    @check_login
    def get(self,request):
        u_id = request.uid
        store = StoreModel.objects.filter(bus_user_id=u_id)
        store_list = []
        for i in store:
            store_list.append({
                'id':i.id,
                'store':i.store,
                'site':i.site,
                'is_default':i.is_default,
                'establish_time':i.establish_time,
                'change_time':i.change_time,
                'delete':i.delete,
            })
        return Response({
            'code':200,
            'msg':'获取成功',
            'data':store_list
        })

    # 进行开店
    @check_login
    def post(self,request):
        u_id = request.uid
        store = request.data.get('store')
        site = request.data.get('site')
        is_default = request.data.get('is_default')

        if not all([store,site,is_default]):
            return Response({
                'code':400,
                'msg':'获取数据为空'
            })

        if is_default == '1':
            sore = StoreModel.objects.filter(is_default=1,bus_user_id=u_id).first()
            if sore:
                sore.is_default = 2
                sore.save()

        StoreModel.objects.create(
            store=store,
            site=site,
            is_default=int(is_default),
            bus_user_id=u_id,
        )
        return Response({
            'code':200,
            'msg':'开店成功'
        })

    @check_login
    def put(self,request):
        # 修改是否默认
        u_id = request.uid
        is_default = request.data.get('is_default')
        s_id = request.data.get('s_id')

        print('>>>>>>>>>',is_default,s_id)

        if is_default == 1:
            sore = StoreModel.objects.filter(is_default=1,bus_user_id=u_id).first()
            if sore:
                sore.is_default = 2
                sore.save()

        try:
            store = StoreModel.objects.get(id=s_id)
        except Exception as e:
            return Response({
                'code':400,
                'msg':'失败'
            })
        store.is_default = int(is_default)
        store.save()

        return Response({
            'code':200,
            'msg':'修改成功'
        })

from fake_useragent import UserAgent
# 爬取美食，进行添加
class ReptileView(APIView):
    @check_login
    def get(self,request):
        urls = request.query_params.get('url')
        url = 'https://www.meishij.net/fenlei/recai/p' + str(urls) + '/'
        u_id = request.uid
        ug = UserAgent()
        headers = {
            'User-Agent': ug.edge
        }

        ccid = requests.get(url, headers=headers)

        ccid.encoding = "UTF-8"

        dada = BeautifulSoup(ccid.text, 'html.parser')

        li = dada.find_all("div", class_='list_s2_item')
        # print('>>>>>',li)
        for i in li:
            # 提取图片
            img_name = str(i.find('div', class_='imgw').a.get('style')).split('(')[1].split(')')[0]
            # 生成文件名
            i_name = str(random.randint(10000, 99999)) + datetime.strftime(datetime.now(), '%Y%m%d%M%H%S') + '.jpg'
            # 重新请求
            img_get = requests.get(img_name)
            with open('./static/' + i_name, 'wb') as f:
                f.write(img_get.content)
            print('>>', img_name)
            # 提取标题
            title = i.find('a', class_='list_s2_item_info').strong.string
            pei = i.find('a', class_='list_s2_item_info').span.string
            # 随机生成库存
            inventory = round(random.randint(10.0, 99.0),2)
            # 随机生成价格
            price = random.uniform(10,100)
            # 店铺获取
            store = StoreModel.objects.filter(bus_user_id=u_id,is_default=1).first()
            if not store:
                return Response({
                    'code':400,
                    'msg':'没有店铺，请开启默认店铺'
                })
            goods = GoodsModel.objects.filter(g_name=title,img='http://127.0.0.1:8000/static/' + i_name,burdening=pei,bus_user_id=u_id)
            # 分类
            cate = CategoryModel.objects.all()
            cate_list = []
            for i in cate:
                cate_list.append(i)
            cates = random.sample(cate_list,1)[0]
            print('>>>>>>>>>',cates)
            if not goods:
                GoodsModel.objects.create(
                    g_name=title,
                    img='http://127.0.0.1:8000/static/' + i_name,
                    burdening=pei,
                    inventory=inventory,
                    price=price,
                    category_id=cates.id,
                    bus_user_id=u_id,
                    store_id=store.id,
                )
        return Response({
            'code':200,
            'msg':'数据添加成功'
        })












